<template>
  <div>
    <el-upload
      :action="action"
      :headers="headers"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-success="onSuccess"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { deleteImage } from '@/api/image'

export default {
  props: {
    fileList: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      action: `${process.env.VUE_APP_BASE_API}/admin/image`,
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  computed: {
    headers() {
      return {
        Authorization: `${getToken()}`,
      };
    },
  },
  methods: {
    // 上传成功
    onSuccess(response, file, fileList) {
      const { code, msg, data } = response;
      if (code !== 1) {
        this.$message({
          message: (msg && `上传失败，失败原因：${msg}`) || "上传失败",
          type: "error",
        });
        this.$emit("onError", data);
      } else {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.$emit("onSuccess", data);
      }
    },
    // 上传失败
    onError(err) {
      const errMsg = (err.message && JSON.parse(err.message)) || "上传失败";
      this.$message({
        message:
          (errMsg.msg && `上传失败，失败原因：${errMsg.msg}`) || "上传失败",
        type: "error",
      });
      this.$emit("onError", err);
    },
    // 预览图片
    onPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 移除图片
    onRemove(data) {
      let name = data.url.slice(data.url.lastIndexOf('/')+1)
      deleteImage(name).then((response) => {
        if (response.code == 1) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.$emit("onRemove", data);
        }
      });
    },
  },
};
</script>

<style>
</style>